package com.github.linkoog.model_designer.utils;

import com.github.linkoog.model_designer.ide.editer.common.Column;
import com.github.linkoog.model_designer.ide.editer.common.ColumnRef;
import com.github.linkoog.model_designer.ide.editer.common.ColumnVo;
import org.jetbrains.yaml.psi.YAMLKeyValue;
import org.jetbrains.yaml.psi.YAMLMapping;
import org.jetbrains.yaml.psi.YAMLScalar;
import org.jetbrains.yaml.psi.YAMLValue;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class YamlReadUtil {


    public static ColumnVo readColumn(YAMLKeyValue columnKeyValue){
        ColumnVo columnVo = ColumnVo.newStringColumnVo();
        columnVo.setName(columnKeyValue.getKeyText());

        if (columnKeyValue.getValue() == null || !(columnKeyValue.getValue() instanceof YAMLMapping)){
            return columnVo;
        }

        YAMLMapping columnMapping = (YAMLMapping)columnKeyValue.getValue();
        ColumnVo.defaultAttributeMap.forEach((key, val) -> {
            YAMLKeyValue attrKeyValue = columnMapping.getKeyValueByKey(key);
            if (attrKeyValue != null){
                columnVo.setField(key, attrKeyValue.getValueText());
            }
        });

        return columnVo;
    }

    public static List<Column> readTableColumns(Map<String, ColumnVo> comcolMap, YAMLMapping columnsMapping){
        List<Column> columns = new ArrayList<>();
        for (YAMLKeyValue columnKeyValue : columnsMapping.getKeyValues()) {
            YAMLValue columnValue = columnKeyValue.getValue();
            if (columnValue instanceof YAMLScalar){
                YAMLScalar yamlScalar = (YAMLScalar) columnValue;
                if (comcolMap != null && !comcolMap.isEmpty()){
                    ColumnVo columnVo = comcolMap.get(yamlScalar.getTextValue());
                    if (columnVo != null){
                        ColumnRef columnRef = new ColumnRef(columnKeyValue.getKeyText(), columnVo);
                        columns.add(columnRef);
                    }
                }
            } else if (columnValue instanceof YAMLMapping){
                ColumnVo columnVo = readColumn(columnKeyValue);
                columns.add(columnVo);
            }
        }
        return columns;
    }



}
